package com.iweb.util;

import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取账号和密码
        String account= req.getParameter("account");
        String password= req.getParameter("password");
        //加密
        password = DigestUtils.md5Hex(password);
        //编写sql语句，查询数据库
        String sql = "SELECT user_attribute FROM users WHERE account =? AND password =?";
        // 执行 SQL 语句
        List<Map<String, Object>> res = JdbcUtil.jdbcBySelect(sql, account, password);
        PrintWriter pw = resp.getWriter();
        if (!res.isEmpty()) {
            // 从结果中获取 user_attribute 的值
            Map<String, Object> row = res.get(0);
            Integer userAttribute = (Integer) row.get("user_attribute");
            if (userAttribute == 1) {
                // 重定向到管理员页面
                resp.sendRedirect(req.getContextPath() + "/welcom1.html");
                pw.print("登录成功，user_attribute: " + userAttribute);
            } else if (userAttribute == 2)  {
                // 重定向到商家页面
                resp.sendRedirect(req.getContextPath() + "/welcome2.html");
            } else if (userAttribute == 3) {
                // 重定向到普通用户页面
                resp.sendRedirect(req.getContextPath() + "/welcome3.html");
            }
        } else {
            // 登录失败，重定向到登录页面并传递错误信息
            resp.sendRedirect(req.getContextPath() + "/login.html?message=0");
        }
    }

}
